
# launch_master_with_rt_cov.py
# Run the user's Modbus master under real-time coverage snapshots.
import sys, os, importlib.util, inspect
from pathlib import Path
from realtime_coverage import RealTimeCoverage

MASTER_PATH = os.environ.get("MASTER_PATH", "./master_embedded_progress.py")
DATASET = os.environ.get("DATASET_TXT", "./hex_from_prompt_grouped.txt")  # optional override
SNAPSHOT_SEC = float(os.environ.get("COV_INTERVAL_SEC", "30"))
CSV_OUT = os.environ.get("COV_CSV", "./master_cov_timeseries.csv")

def load_module_from_path(path, module_name="user_master_mod"):
    spec = importlib.util.spec_from_file_location(module_name, path)
    mod = importlib.util.module_from_spec(spec)
    sys.modules[module_name] = mod
    spec.loader.exec_module(mod)  # type: ignore
    return mod

def main():
    rt = RealTimeCoverage(interval_sec=SNAPSHOT_SEC, out_csv=CSV_OUT, branch=True, concurrency=("thread",))
    rt.start()
    try:
        mod = load_module_from_path(MASTER_PATH, "user_master_mod")
        # Best effort: override TXT_PATH if present
        if DATASET and hasattr(mod, "TXT_PATH"):
            setattr(mod, "TXT_PATH", DATASET)
            print(f"[INFO] Overridden TXT_PATH -> {getattr(mod, 'TXT_PATH')}")
        # Ensure host/port can be overridden if constants exist
        if os.environ.get("MASTER_HOST") and hasattr(mod, "HOST"):
            setattr(mod, "HOST", os.environ["MASTER_HOST"])
        if os.environ.get("MASTER_PORT") and hasattr(mod, "PORT"):
            try:
                setattr(mod, "PORT", int(os.environ["MASTER_PORT"]))
            except Exception:
                pass

        entry = getattr(mod, "main", None)
        if entry is None:
            # Fallback: execute as script
            import runpy
            runpy.run_path(MASTER_PATH, run_name="__main__")
        else:
            entry()
    finally:
        rt.stop()

if __name__ == "__main__":
    main()
